use std::mem::ManuallyDrop;

use core_graphics::{CGContext, CGFloat, CGPoint, CGRect};
use foundation::NSData;
use objc_derive::{objc_impl, selector_impl};
use uikit::{UIColor, UIImage};

use crate::main_vc::LOGO;

pub(crate) struct CustomView {}

impl CustomView {
  pub(crate) fn new() -> Self {
    Self {}
  }
}

#[objc_impl(UIView)]
impl CustomView {
  #[selector_impl("drawRect:")]
  fn draw(&self, _this: &objc::runtime::Object, rect: CGRect) {
    let ctx = ManuallyDrop::new(CGContext::new());
    let top_x = rect.size.width * 0.5;
    let top_y: CGFloat = rect.size.height * 0.5 - 100.0;
    let top_radius: CGFloat = 50.0;
    ctx.add_arc(CGPoint::new(top_x, top_y), top_radius, 0.0, std::f64::consts::PI, true);
    let body_x = top_x - top_radius;
    ctx.move_to_point(CGPoint::new(body_x, top_y));
    ctx.add_line_to_point(CGPoint::new(body_x, top_y + 100.0));
    ctx.add_arc(CGPoint::new(top_x, top_y + 100.0), top_radius, std::f64::consts::PI, 0.0, true);
    ctx.add_line_to_point(CGPoint::new(top_x + top_radius, top_y));
    UIColor::yellow_color().set();
    ctx.fill_path();
    let x = rect.size.width * 0.5;
    let y = rect.size.height * 0.5;
    let margin: CGFloat = 30.0;
    let distance: CGFloat = 20.0;
    ctx.move_to_point(CGPoint::new(x - margin, y - distance));
    ctx.add_quad_curve_to_point(CGPoint::new(x + margin, y - distance), CGPoint::new(x, y));
    UIColor::black_color().set();
    ctx.stroke_path();

    let rect = CGRect::make(150., 80., 100., 100.);
    let rrect = CGRect::make(150., 80., 90., 90.);
    ctx.add_ellipse_in_rect(rrect);
    ctx.clip();
    ctx.fill_path();

    let image = {
      let data = NSData::data_with_bytes_length(LOGO, LOGO.len());
      UIImage::image_with_data(data)
    };
    // image.draw_at_point(CGPoint::new(150., 80.));
    image.draw_in_rect(rect);
  }
}
